from django.core.management.base import BaseCommand, CommandError
from django import apps
from django.db import transaction
from django.contrib.auth.models import Group
from apps.user.models import TunLevel
from apps.system.models import SystemSetting
from decimal import Decimal as D
import requests
import json
from urllib.parse import quote
import os

top = '中国'
query_url = 'http://www.sf-express.com/sf-service-owf-web/service/region/live/origin?lang=sc&region=cn&translate=&query=%s&limit=500&level=3'
data = {}


class Command(BaseCommand):
    help = "Init data for models which has init_data var"

    def handle(self, *args, **options):
        # 国家
        states = self.get_content(['states', ])
        data['states'] = {}
        for state in states:
            state = self.clean_item(state)
            data['states'][state['code']] = state
            # 省
            provinces = self.get_content(['states', state['code']])
            data['states'][state['code']]['provinces'] = []
            data['states'][state['code']]['citys'] = {}
            data['states'][state['code']]['xians'] = {}
            for province in provinces:
                province = self.clean_item(province)
                data['states'][state['code']]['provinces'].append(province)
                # 市
                data['states'][state['code']]['citys'][province['code']] = []
                citys = self.get_content(['states', state['code'], province['code']])
                for city in citys:
                    city = self.clean_item(city)
                    data['states'][state['code']]['citys'][province['code']].append(city)
                    # 县
                    data['states'][state['code']]['xians'][province['code']+'-'+city['code']] = []
                    xians = self.get_content(['states', state['code'], province['code'], city['code']])
                    for xian in xians:
                        xian = self.clean_item(xian)
                        data['states'][state['code']]['xians'][province['code']+'-'+city['code']].append(xian)

        with open('full-address.json', 'w') as f:
            f.write(json.dumps(data))

    def clean_item(self, item):
        return {
            'code': item['code'],
            'name': item['name'],
        }

    def cache_request_result(self, content, paths):
        print(paths, len(content))
        file_path = '-'.join(paths) + '.json'
        with open(file_path, 'w') as f:
            f.write(json.dumps(content))

    def get_content(self, paths):
        print(paths)
        file_path = '-'.join(paths) + '.json'
        if os.path.exists(file_path):
            with open(file_path) as f:
                content = json.loads(f.read())
        else:
            if len(paths) == 1:
                content = self.get_states()
            elif len(paths) == 2:
                content = self.get_provinces({'code': paths[-1]})
            elif len(paths) == 3:
                content = self.get_citys({'code': paths[-1]})
            elif len(paths) == 4:
                content = self.get_xians({'code': paths[-1]})
            else:
                content = 'ERROR'
            self.cache_request_result(content, paths)
        return content

    def get_states(self):
        current_query = query_url % quote(top)
        print('STATE:', current_query)
        items = requests.get(current_query).json()
        return items

    def get_provinces(self, state):
        current_query = 'http://www.sf-express.com/sf-service-owf-web/service/region/%s/subRegions/origins?level=1&lang=sc&region=cn&translate=' % state['code']
        print('PROVINCE:', current_query)
        items = requests.get(current_query).json()
        return items

    def get_citys(self, province):
        current_query = 'http://www.sf-express.com/sf-service-owf-web/service/region/%s/subRegions/origins?level=2&lang=sc&region=cn&translate=' % province['code']
        print('CITY:', current_query)
        items = requests.get(current_query).json()
        return items

    def get_xians(self, city):
        current_query = 'http://www.sf-express.com/sf-service-owf-web/service/region/%s/subRegions/origins?level=3&lang=sc&region=cn&translate=' % city['code']
        print('XIAN:', current_query)
        items = requests.get(current_query).json()
        return items

